<?php
/**
 * 扩展变量逻辑层
 * @author maniac
 */
namespace app\common\logic;

use app\common\model\Vars AS VarsModel;

class Vars extends Base
{
    /**
     * 添加/编辑扩展变量
     * @param  array $data 请求的信息
     */
    public function save($data)
    {
        $result = parent::save($data);
        if ($result) {
            $this->writeConfig($data);
        }
        return $result;
    }
    
    /**
     * 写入扩展变量配置文件
     * @param  array $data 请求的信息
     */
    private function writeConfig($data)
    {
        $file = \think\facade\Env::get('config_path') . 'vars.php';
        $vars = VarsModel::withTrashed()->field('id,title,key,value')->order('id ASC')->select();
        $str  = "<?php\n"
               ."/**\n"
               ." * 扩展变量配置文件\n"
               ." * @author maniac\n"
               ." */\n"
               ."return [\n";
        foreach ($vars as $v) {
            $str .= "\t'public_{$v['key']}' => '{$v['value']}',\t\t// {$v['title']}\n";
        }
        $str .= "];\n";
        file_put_contents($file, $str);
    }
}
